package com.gdziarmaga.webshop.web.managedBeans.book;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;

import org.richfaces.event.FileUploadEvent;
import org.richfaces.model.UploadedFile;
import org.springframework.beans.factory.annotation.Autowired;

import com.gdziarmaga.webshop.allegro.client.WebshopAllegroAPI;
import com.gdziarmaga.webshop.author.model.Author;
import com.gdziarmaga.webshop.author.services.AuthorManager;
import com.gdziarmaga.webshop.book.model.Book;
import com.gdziarmaga.webshop.book.services.BookManager;
import com.gdziarmaga.webshop.utils.filtering.BaseFilter;
import com.gdziarmaga.webshop.utils.filtering.FilterComparisonType;
import com.gdziarmaga.webshop.utils.filtering.FilterField;
import com.gdziarmaga.webshop.utils.springcontext.AppContext;
import com.gdziarmaga.webshop.web.menus.AdminPanelBean;
import com.gdziarmaga.webshop.web.utils.FacesUtils;

@ManagedBean(name = "bookRegisterBean")
@ViewScoped
public class BookRegisterBean {

	@Autowired
	private BookManager bookManager;

	@Autowired
	private AuthorManager authorManager;

	private Collection<SelectItem> authors_list;

	private Author oneAuthor;

	private String select;

	private Collection<UploadedFile> uploadedFile;

	private List<UploadedFile> iconData = new ArrayList<UploadedFile>();

	public Collection<UploadedFile> getUploadedFile() {
		return uploadedFile;
	}

	public void setUploadedFile(Collection<UploadedFile> uploadedFile) {
		this.uploadedFile = uploadedFile;
	}

	public String getSelect() {
		return select;
	}

	public void setSelect(String select) {
		this.select = select;
	}

	private List<Author> selected_authors;

	public List<Author> getSelected_authors() {
		if (selected_authors == null) {
			selected_authors = new ArrayList<Author>();
		}
		return selected_authors;
	}

	public void setSelected_authors(List<Author> selected_authors) {
		this.selected_authors = selected_authors;
	}

	public void uploadFile(FileUploadEvent event) throws Exception {
		iconData.add(event.getUploadedFile());

	}

	public Collection<SelectItem> getAuthors_list() {
		if (authors_list == null) {
			authors_list = new ArrayList<SelectItem>();
			List<Author> all = authorManager.getAll();
			for (Author author : all) {
				authors_list.add(new SelectItem(author, author
						.getAuthor_first_name()
						+ " "
						+ author.getAuthor_last_name()));
			}
		}
		return authors_list;
	}

	public void addAuthorToList(ActionEvent event) {
		BaseFilter filter = new BaseFilter();
		filter.addFilterField(new FilterField<String>(select.split(" ")[0],
				"author_first_name", FilterComparisonType.EQUAL));
		filter.addFilterField(new FilterField<String>(select.split(" ")[1],
				"author_last_name", FilterComparisonType.EQUAL));
		Author author = authorManager.getAuthorByFilter(filter).get(0);
		if (author != null && !getSelected_authors().contains(author)) {
			getSelected_authors().add(author);
		}
	}

	public SelectItem[] getMenuItems() {
		if (getSelected_authors().isEmpty()) {
			return null;
		} else {
			SelectItem[] items = new SelectItem[getSelected_authors().size()];
			int i = 0;
			for (Author author : getSelected_authors()) {
				items[i] = new SelectItem(author, author.getAuthor_first_name()
						+ " " + author.getAuthor_last_name());
				i++;
			}
			return items;
		}
	}

	public void saveAndAddAuthorToList(ActionEvent event) {
		if (oneAuthor != null && !getSelected_authors().contains(oneAuthor)) {
			authorManager.saveAuthor(oneAuthor);
			getSelected_authors().add(oneAuthor);
		}
	}

	public void setAuthors_list(Collection<SelectItem> authors_list) {
		this.authors_list = authors_list;
	}

	@PostConstruct
	public void init() {
		bookManager = (BookManager) AppContext.getApplicationContext().getBean(
				"bookManager");
		authorManager = (AuthorManager) AppContext.getApplicationContext()
				.getBean("authorManager");
	}

	private Book book;

	public void createBook(ActionEvent event) throws IOException {
		if (book.getBook_id() == 0) {
			Set<Author> set = new HashSet<Author>();
			for (Author author : getSelected_authors()) {
				set.add(author);
			}
			book.setAuthor_set(set);
			byte[] dane1 = iconData.get(0).getData();
			byte[] dane2 = iconData.get(1).getData();
			if (dane1.length > dane2.length) {
				OutputStream os = new FileOutputStream(FacesUtils
						.getServletContext().getRealPath("/")
						+ "resources\\images\\book_icons\\Java\\big\\"
						+ book.getIsbn() + ".jpg");
				os.write(dane1, 0, dane1.length);
				os.close();

				OutputStream os2 = new FileOutputStream(FacesUtils
						.getServletContext().getRealPath("/")
						+ "resources\\images\\book_icons\\Java\\small\\"
						+ book.getIsbn() + ".jpg");
				os2.write(dane2, 0, dane2.length);
				os2.close();

			} else {
				OutputStream os = new FileOutputStream(FacesUtils
						.getServletContext().getRealPath("/")
						+ "resources\\images\\book_icons\\Java\\big\\"
						+ book.getIsbn() + ".jpg");
				os.write(dane2, 0, dane2.length);
				os.close();

				OutputStream os2 = new FileOutputStream(FacesUtils
						.getServletContext().getRealPath("/")
						+ "resources\\images\\book_icons\\Java\\small\\"
						+ book.getIsbn() + ".jpg");
				os2.write(dane1, 0, dane1.length);
				os2.close();
			}
			WebshopAllegroAPI.sellBook(book, FacesUtils.getServletContext()
					.getRealPath("/"));
		}
		bookManager.saveBook(book);
		book = null;
	}

	public void cancelBookEdit(ActionEvent e) {
		book = null;
	}

	public Book getBook() {
		if (book == null) {
			if (!editBook()) {
				book = new Book();
			}
		}
		return book;
	}

	public void setBook(Book book) {
		this.book = book;
	}

	public boolean editBook() {
		AdminPanelBean bean = ((AdminPanelBean) FacesUtils.getRequest()
				.getSession().getAttribute("adminPanelBean"));
		if (!bean.getSelectionItems().isEmpty()) {
			if (bean.getSelectionItems().get(0) instanceof Book) {
				Long id = ((Book) bean.getSelectionItems().get(0)).getBook_id();
				setBook(bookManager.getBookById(id));
				return true;
			}
		}
		return false;
	}

	public void removeBook() {
		AdminPanelBean bean = ((AdminPanelBean) FacesUtils.getRequest()
				.getSession().getAttribute("adminPanelBean"));
		Long id = ((Book) bean.getSelectionItems().get(0)).getBook_id();
		if (id != null) {
			bookManager.deleteBook(id);
		}
	}

	public void setOneAuthor(Author oneAuthor) {
		this.oneAuthor = oneAuthor;
	}

	public Author getOneAuthor() {
		if (oneAuthor == null) {
			oneAuthor = new Author();
		}
		return oneAuthor;
	}

}
